import router from '@/router'
import store from '@/store'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const whiteList = ['/login', '/register']

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  const token = getToken()
  if (token) {
    if (to.path === '/login') {
      // 已经登录,重定向到主页
      console.log('permission/已经登录,回到首页')
      next({ path: '/' })
      NProgress.done()
    } else {
      const name = store.getters.name
      if (name) {
        // 已经获取用户信息
        next()
        NProgress.done()
      } else {
        try {
          // 获取用户信息
          // await store.dispatch('user/getInfo')
          // console.log('/permission用户信息:', store.getters.name)
          next()
          NProgress.done()
        } catch (error) {
          // 移除token并重新登录
        }
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) >= 0) {
      // 白名单不需要登录
      next()
      NProgress.done()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})
